import jwt
from app.config import (
    SECRET_KEY,
    REDIS_USER_PREFIX, REDIS_USER_EXPIRE
)
from app.exception.cus_exception import TokenInvalidException
from db.redis_part import xibie_redis

def get_user_token(user_id):
    token = xibie_redis.hget(f'{REDIS_USER_PREFIX}{user_id}', 'token')
    if token is None:
        token = jwt.encode({'user_id': user_id}, SECRET_KEY, algorithm='HS256')
        xibie_redis.hset(name=f'{REDIS_USER_PREFIX}{user_id}', mapping={'token': token})
        xibie_redis.expire(f'{REDIS_USER_PREFIX}{user_id}', REDIS_USER_EXPIRE)
    return token
    

def get_user_id_by_token(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
    except Exception as e:
        raise TokenInvalidException()
    if 'user_id' in payload and payload['user_id']:
        if xibie_redis.hget(f'{REDIS_USER_PREFIX}{payload["user_id"]}', 'token') == token:
            return payload['user_id']
        else:
            raise TokenInvalidException()
    else:
        raise TokenInvalidException()
